package com.mini.service;

import com.mini.config.BusinessException;
import com.mini.constant.CooApplyPersonEnum;
import com.mini.constant.CooManagerTypeEnum;
import com.mini.constant.CooOperationEnum;
import com.mini.constant.CooTabTypeEnum;
import com.mini.model.BusinessCity;
import com.mini.model.BusinessCooperativeBean;
import com.mini.repository.CooperativeRepository;
import com.mini.req.CooperativeFindReq;
import com.mini.req.CooperativeReq;
import com.mini.req.CooperativeUpdateReq;
import com.mini.res.CooperativeLoadRes;
import com.mini.res.CooperativeShowRes;
import com.mini.util.CheckObjectIsNullUtils;
import com.mini.util.SnowFlake;
import com.mini.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目名称：traditional-business
 * 类 名 称：CooperativeService
 * 类 描 述：TODO
 * 创建时间：2020/12/2 下午2:02
 * 创 建 人：zhanghuiying
 */
@Slf4j
@Service
public class CooperativeService extends BaseService {

    @Autowired
    private CooperativeRepository cooperativeRepository;
    @Autowired
    private DictionariesBaseService dictionariesBaseService;
    @Autowired
    private MiniAdminService miniAdminService;
    @Autowired
    private CooperativeAndPlanLogRecordService operationRecordService;

    /*
     * @name: updateCooperative
     * @description: 确认／撤销／解除合作申请
     * @param cooperativeUpdateVO
     * @return: Boolean
     * @date: 2020/12/3 上午11:28
     * @auther: zhanghuiying
     */
    public Boolean updateCooperative(CooperativeUpdateReq cooperativeUpdateVO, String Authorization) {
        Long userId = miniAdminService.getLoginUserId(Authorization);
        if (Objects.isNull(userId)) {
            throw new BusinessException("token解析失败,请稍后重试或重新登陆！");
        }
        boolean b = CheckObjectIsNullUtils.objCheckIsNull(cooperativeUpdateVO);
        if (!b) {
            throw new BusinessException("实体内参数必须有值！");
        }
        try {
//          加分布式锁更新
            if (tryLock("updateCooperative" + cooperativeUpdateVO.getId().toString())) {
                BusinessCooperativeBean businessCooperativeBean = cooperativeRepository.findOne(cooperativeUpdateVO.getId());
                if (businessCooperativeBean == null) {
                    throw new BusinessException("数据不存在");
                }
                if (cooperativeUpdateVO.getCooperativeState() > CooOperationEnum.remove.getCode() || cooperativeUpdateVO.getCooperativeState() < CooOperationEnum.confirm.getCode()) {
                    throw new BusinessException("更新类型不合法");
                }
                if (cooperativeUpdateVO.getApplyUser() == CooManagerTypeEnum.throwManager.getCode() && businessCooperativeBean.getCooperativeType() == CooManagerTypeEnum.sellManager.getCode() && cooperativeUpdateVO.getCooperativeState() == CooOperationEnum.undo.getCode()
                        || cooperativeUpdateVO.getApplyUser() == CooManagerTypeEnum.sellManager.getCode() && businessCooperativeBean.getCooperativeType() == CooManagerTypeEnum.throwManager.getCode() && cooperativeUpdateVO.getCooperativeState() == CooOperationEnum.undo.getCode()) {
                    throw new BusinessException("该撤销操作不合法");
                }
                if (cooperativeUpdateVO.getApplyUser() == CooManagerTypeEnum.throwManager.getCode() && businessCooperativeBean.getCooperativeType() == CooManagerTypeEnum.throwManager.getCode() && cooperativeUpdateVO.getCooperativeState() == CooOperationEnum.confirm.getCode()
                        || cooperativeUpdateVO.getApplyUser() == CooManagerTypeEnum.sellManager.getCode() && businessCooperativeBean.getCooperativeType() == CooManagerTypeEnum.sellManager.getCode() && cooperativeUpdateVO.getCooperativeState() == CooOperationEnum.confirm.getCode()) {
                    throw new BusinessException("该确认操作不合法");
                }
                if (businessCooperativeBean.getCooperativeState() == 3 && cooperativeUpdateVO.getCooperativeState() == 2) {
                    throw new BusinessException("该条记录已经撤销，请刷新页面！");
                }
                if (businessCooperativeBean.getCooperativeState() == 2 && cooperativeUpdateVO.getCooperativeState() == 3) {
                    throw new BusinessException("该条记录已经同意合作，请刷新页面！");
                }
                businessCooperativeBean.setCooperativeState(cooperativeUpdateVO.getCooperativeState());
                businessCooperativeBean.setUpdateUserId(userId);
                cooperativeRepository.save(businessCooperativeBean);
                // 保存操作记录
                try {
                    asyncTaskManager.getExecutor().submit(new Runnable() {
                        @Override
                        public void run() {
                            if (cooperativeUpdateVO.getCooperativeState() == CooOperationEnum.remove.getCode()) {
                                operationRecordService.CooperativeLog(userId, CooTabTypeEnum.cooperativeList.getCode(),cooperativeUpdateVO.getApplyUser(), cooperativeUpdateVO.getCooperativeState(), businessCooperativeBean,Authorization);
                                log.error("合作管理 合作状态更改 日志记录");
                            } else {
                                operationRecordService.CooperativeLog(userId, CooTabTypeEnum.applyList.getCode(), cooperativeUpdateVO.getApplyUser(),cooperativeUpdateVO.getCooperativeState(), businessCooperativeBean,Authorization);
                                log.error("合作管理 合作状态更改 日志记录");
                            }
                        }
                    });
                } catch (Exception e) {
                    log.error("合作管理 合作状态更改 日志记录异常", e);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        } finally {
            releaseLockKey("updateCooperative" + cooperativeUpdateVO.getId().toString());
        }
        return true;
    }

    /*
     * @name: deleteCooperative
     * @description: 删除合作
     * @param manageType
     * @param listType
     * @param id
     * @param userId
     * @return: Boolean
     * @date: 2020/12/3 上午11:27
     * @auther: zhanghuiying
     */
    public Boolean deleteCooperative(Integer manageType, Integer listType, Long id, String Authorization) {
        Long userId = miniAdminService.getLoginUserId(Authorization);
        if (Objects.isNull(userId)) {
            throw new BusinessException("token解析失败,请稍后重试或重新登陆！");
        }
        BusinessCooperativeBean businessCooperativeBean = cooperativeRepository.findOne(id);
        if (Objects.isNull(businessCooperativeBean)) {
            throw new BusinessException("删除的数据不存在！");
        }
        businessCooperativeBean.setUpdateUserId(userId);

        if (manageType == CooManagerTypeEnum.throwManager.getCode() && listType == CooTabTypeEnum.applyList.getCode()) {
            setThrowApplyDelete(businessCooperativeBean);
            // 保存操作记录
            try {
                asyncTaskManager.getExecutor().submit(new Runnable() {
                    @Override
                    public void run() {
                        operationRecordService.CooperativeLog(userId, listType,manageType, CooOperationEnum.delete.getCode(), businessCooperativeBean,Authorization);
                        log.error("合作管理 合作删除 日志记");
                    }
                });
            } catch (Exception e) {
                log.error("合作管理 合作删除 日志记录异常", e);
            }
            return true;
        }
        if (manageType == CooManagerTypeEnum.sellManager.getCode() && listType == CooTabTypeEnum.applyList.getCode()) {
            setSellApplyDelete(businessCooperativeBean);
            // 保存操作记录
            try {
                asyncTaskManager.getExecutor().submit(new Runnable() {
                    @Override
                    public void run() {
                        operationRecordService.CooperativeLog(userId, listType,manageType, CooOperationEnum.delete.getCode(), businessCooperativeBean,Authorization);
                        log.error("合作管理 合作删除 日志记");
                    }
                });
            } catch (Exception e) {
                log.error("合作管理 合作删除 日志记录异常", e);
            }
            return true;
        }
        if (manageType == CooManagerTypeEnum.throwManager.getCode() && listType == CooTabTypeEnum.cooperativeList.getCode()) {
            setThrowCooperativeDelete(businessCooperativeBean);
            // 保存操作记录
            try {
                asyncTaskManager.getExecutor().submit(new Runnable() {
                    @Override
                    public void run() {
                        operationRecordService.CooperativeLog(userId, listType,manageType, CooOperationEnum.delete.getCode(), businessCooperativeBean,Authorization);
                        log.error("合作管理 合作删除 日志记");
                    }
                });
            } catch (Exception e) {
                log.error("合作管理 合作删除 日志记录异常", e);
            }
            return true;
        }
        if (manageType == CooManagerTypeEnum.sellManager.getCode() && listType == CooTabTypeEnum.cooperativeList.getCode()) {
            setSellcooperativeDelete(businessCooperativeBean);
            // 保存操作记录
            try {
                asyncTaskManager.getExecutor().submit(new Runnable() {
                    @Override
                    public void run() {
                        operationRecordService.CooperativeLog(userId, listType,manageType, CooOperationEnum.delete.getCode(), businessCooperativeBean,Authorization);
                        log.error("合作管理 合作删除 日志记");
                    }
                });
            } catch (Exception e) {
                log.error("合作管理 合作删除 日志记录异常", e);
            }
            return true;
        }
        return false;
    }

    public void setSellApplyDelete(BusinessCooperativeBean businessCooperativeBean) {
        businessCooperativeBean.setSellApplyDelete(0);
        cooperativeRepository.save(businessCooperativeBean);
        return;
    }

    public void setSellcooperativeDelete(BusinessCooperativeBean businessCooperativeBean) {
        businessCooperativeBean.setSellCooperativeDelete(0);
        cooperativeRepository.save(businessCooperativeBean);
        return;
    }

    public void setThrowApplyDelete(BusinessCooperativeBean businessCooperativeBean) {
        businessCooperativeBean.setThrowApplyDelete(0);
        cooperativeRepository.save(businessCooperativeBean);
        return;
    }

    public void setThrowCooperativeDelete(BusinessCooperativeBean businessCooperativeBean) {
        businessCooperativeBean.setThrowCooperativeDelete(0);
        cooperativeRepository.save(businessCooperativeBean);
        return;
    }

    /*
     * @name: addCooperativeApply
     * @description: 添加合作申请
     * @param CooperativeReq
     * @return: Boolean
     * @date: 2020/12/3 下午5:53
     * @auther: zhy
     */
    @Transactional
    public Boolean addCooperativeApply(CooperativeReq cooperativeVO, String Authorization) {
        StopWatch sw = new StopWatch();
        sw.start();
        boolean b = CheckObjectIsNullUtils.objCheckIsNull(cooperativeVO);
        if (!b) {
            throw new BusinessException("传入参数不合法！");
        }
        Long userId = miniAdminService.getLoginUserId(Authorization);
        if (Objects.isNull(userId)) {
            throw new BusinessException("token解析失败,请稍后重试或重新登陆！");
        }
//      获取项目省份渠道名称列表
        Map<Integer, String> projectMap = getProjectMap(Authorization);
        Map<String, String> channelMap = getChannelMap(Authorization);
        Map<String, String> provinceMap = getProvinceMap(Authorization);
        cooperativeVO.getThrowProvinceCodeList().stream()
                .forEach(t -> {
                    try {
                        if (tryLock("addCooperativeApply" + cooperativeVO.getQuantumArmyGroupId().toString() + cooperativeVO.getThrowUserId().toString() + cooperativeVO.getProjectId().toString() + cooperativeVO.getAdChannelCode() + t)) {
                            String provinceName = provinceMap.get(t);
                            String projectName = projectMap.get(cooperativeVO.getProjectId());
                            String channelName = channelMap.get(cooperativeVO.getAdChannelCode());
                            List<BusinessCooperativeBean> result = cooperativeRepository.findByQuantumArmyGroupIdAndThrowUserIdAndProjectIdAndAdChannelCodeAndThrowProvinceCode(cooperativeVO.getQuantumArmyGroupId(), cooperativeVO.getThrowUserId(), cooperativeVO.getProjectId(), cooperativeVO.getAdChannelCode(), t);
                            if (!CollectionUtils.isEmpty(result)) {
                                for (BusinessCooperativeBean res :
                                        result) {
                                    if (res.getCooperativeState() != 3 && res.getCooperativeState() != 4) {
                                        releaseLockKey("addCooperativeApply" + cooperativeVO.getQuantumArmyGroupId().toString() + cooperativeVO.getThrowUserId().toString() + cooperativeVO.getProjectId().toString() + cooperativeVO.getAdChannelCode() + t);
                                        String quantumArmyGroupName = miniAdminService.getDeptName(cooperativeVO.getQuantumArmyGroupId());
                                        UserVO userSimple = miniAdminService.getUserSimpleInfo(cooperativeVO.getThrowUserId());
                                        throw new BusinessException("【" + quantumArmyGroupName + "/" + userSimple.getNickname() + "/" + projectName + "/" + channelName + "/" + provinceName + "】的合作申请正在申请或已达成合作，请更换条件重新尝试");
                                    }
                                }
                            }
                            BusinessCooperativeBean businessCooperativeBean = new BusinessCooperativeBean();
                            BeanUtils.copyProperties(cooperativeVO, businessCooperativeBean);
                            long id = SnowFlake.nextId();
                            businessCooperativeBean.setId(id);
                            businessCooperativeBean.setCooperativeState(1);
                            businessCooperativeBean.setSellCooperativeDelete(1);
                            businessCooperativeBean.setSellApplyDelete(1);
                            businessCooperativeBean.setThrowCooperativeDelete(1);
                            businessCooperativeBean.setThrowApplyDelete(1);
                            businessCooperativeBean.setThrowProvinceCode(t);
                            businessCooperativeBean.setCreateUserId(userId);
                            cooperativeRepository.save(businessCooperativeBean);
                            log.info("添加合作申请成功，参数{}", cooperativeVO);
                            // 保存操作记录
                            try {
                                asyncTaskManager.getExecutor().submit(new Runnable() {
                                    @Override
                                    public void run() {
                                        operationRecordService.CooperativeLog(userId, CooTabTypeEnum.applyList.getCode(),cooperativeVO.getCooperativeType(), CooOperationEnum.create.getCode(), businessCooperativeBean,Authorization);
                                        log.info("合作管理 添加合作记录 日志记录");
                                    }
                                });
                            } catch (Exception e) {
                                log.error("合作管理 添加合作记录 日志记录异常", e);
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw new BusinessException(e.getMessage());
                    } finally {
                        log.info("释放锁");
                        releaseLockKey("addCooperativeApply" + cooperativeVO.getQuantumArmyGroupId().toString() + cooperativeVO.getThrowUserId().toString() + cooperativeVO.getProjectId().toString() + cooperativeVO.getAdChannelCode() + t);
                    }
                });
        sw.stop();
        log.info("方法耗时：{}", sw.getTotalTimeMillis());
        return true;
    }

    /*
     * @name:  findThrowCooperativeApplyList
     * @description: 查询投放合作列表
     * @param CooperativeFindReq
     * @return: CooperativeLoadRes
     * @date: 2020/12/6 下午2:15
     * @auther: zhy
     */
    public CooperativeLoadRes findThrowCooperativeApplyList(Integer cooType, String authorization, CooperativeFindReq cooperativeFindReq, Integer listType) {
        StopWatch sw = new StopWatch();
        sw.start();
        Long userId = miniAdminService.getLoginUserId(authorization);
        if (Objects.isNull(userId)) {
            throw new BusinessException("token解析失败,请稍后重试或重新登陆！");
        }
        List<Long> idList = new ArrayList<>();
        if (Objects.isNull(cooperativeFindReq.getQuantumArmyGroupId())) {
            //根据token查询量子军团id集合
            List<DeptVO> deptlist = miniAdminService.getWorkRoomDeptList(authorization);
            if (!CollectionUtils.isEmpty(deptlist)) {
                List<Long> deptIds = deptlist.stream().map(deptVO -> deptVO.getId()).collect(Collectors.toList());
                idList.addAll(deptIds);
            } else {
                return null;
            }
        } else {
            idList.add(cooperativeFindReq.getQuantumArmyGroupId());
        }
        log.info("查询所有量子军团成功：{}", idList);
        Integer cooperativeType = 0;
        if (null != cooperativeFindReq.getApplyUser()) {
//            根据页面类型和申请方 拿到查询的合作类型
            cooperativeType = setCooperativeType(cooType, cooperativeFindReq.getApplyUser());
        }
//        分页查询投放合作列表
        Specification<BusinessCooperativeBean> cooperativeList = getThrowList(cooperativeFindReq, cooperativeType, idList, listType);
        log.info("sql封装成功！");
        Pageable pageable = buildPageRequest(cooperativeFindReq.getPageNumber(), cooperativeFindReq.getPageSize(), new Sort(Sort.Direction.DESC, "createTime"));
        Page<BusinessCooperativeBean> businessCooperativeBeans = cooperativeRepository.findAll(cooperativeList, pageable);
        log.info("分页查询投放列表成功：{}", businessCooperativeBeans.getContent());
//        根据字段的id，查询相关名称并赋值，统计条数
        CooperativeLoadRes cooperativeLoadRes = setName(businessCooperativeBeans.getContent(), authorization, cooType, listType);
        cooperativeLoadRes.setTotalElements(businessCooperativeBeans.getTotalElements());
        cooperativeLoadRes.setTotalPages(businessCooperativeBeans.getTotalPages());
        log.info("相关名称赋值结束：{}", cooperativeLoadRes);
//        查询最新数据条数
        Integer count = findCount(cooType, idList);
        cooperativeLoadRes.setNewSize(count);
        sw.stop();
        log.info("方法耗时：{}", sw.getTotalTimeMillis());
        return cooperativeLoadRes;
    }

    /*
     * @name:
     * @description: 查询投放合作列表封装sql
     * @return: Specification<BusinessCooperativeBean>
     * @date: 2020/12/6 上午11:28
     * @auther: zhy
     */
    public Specification<BusinessCooperativeBean> getThrowList(CooperativeFindReq cooperativeFindReq, Integer cooperativeType, List<Long> quantumArmyGroupIdList, Integer listType) {
        return new Specification<BusinessCooperativeBean>() {
            @Override
            public Predicate toPredicate(Root<BusinessCooperativeBean> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (null != cooperativeFindReq.getThrowUserId()) {
                    Predicate throwUserId = cb.equal(root.get("throwUserId").as(Integer.class), cooperativeFindReq.getThrowUserId());
                    predicates.add(throwUserId);
                }
                if (null != cooperativeFindReq.getThrowRoomId()) {
                    Predicate throwRoomId = cb.equal(root.get("throwRoomId").as(Integer.class), cooperativeFindReq.getThrowRoomId());
                    predicates.add(throwRoomId);
                }
                if (null != cooperativeFindReq.getArmyGroupId()) {
                    Predicate armyGroupId = cb.equal(root.get("armyGroupId").as(Integer.class), cooperativeFindReq.getArmyGroupId());
                    predicates.add(armyGroupId);
                }
                if (null != cooperativeFindReq.getProjectId()) {
                    Predicate projectId = cb.equal(root.get("projectId").as(Integer.class), cooperativeFindReq.getProjectId());
                    predicates.add(projectId);
                }
                if (StringUtils.isNotBlank(cooperativeFindReq.getAdChannelCode())) {
                    Predicate adChannelCode = cb.equal(root.get("adChannelCode").as(String.class), cooperativeFindReq.getAdChannelCode());
                    predicates.add(adChannelCode);
                }
                if (StringUtils.isNotBlank(cooperativeFindReq.getThrowProvinceCode())) {
                    Predicate throwProvinceCode = cb.equal(root.get("throwProvinceCode").as(String.class), cooperativeFindReq.getThrowProvinceCode());
                    predicates.add(throwProvinceCode);
                }
                Integer coo = cooperativeType;
                if (0 != cooperativeType) {
                    Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                    predicates.add(cooperativeType);
                } else if (0 == cooperativeType && null != cooperativeFindReq.getApplyState() && listType == CooTabTypeEnum.applyList.getCode()) {
                    if (cooperativeFindReq.getApplyState() == 2) {
                        coo = CooManagerTypeEnum.sellManager.getCode();
                        Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                        predicates.add(cooperativeType);
                    } else if (cooperativeFindReq.getApplyState() == 1) {
                        coo = CooManagerTypeEnum.throwManager.getCode();
                        Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                        predicates.add(cooperativeType);
                    }
                }
                Integer state = 0;
                if (null != cooperativeFindReq.getApplyState()) {
                    state = cooperativeFindReq.toApplyState(cooperativeFindReq.getApplyState());
                    if (null != cooperativeFindReq.getApplyUser()) {
                        if (cooperativeFindReq.getApplyUser() == CooApplyPersonEnum.myself.getCode() && cooperativeFindReq.getApplyState() == 2 || cooperativeFindReq.getApplyUser() == CooApplyPersonEnum.other.getCode() && cooperativeFindReq.getApplyState() == 1) {
                            state = -1;
                        }
                    }
                }
                if (0 != state) {
                    if (state == CooOperationEnum.confirm.getCode() && listType == CooTabTypeEnum.applyList.getCode()) {
                        Predicate cooperativeState1 = cb.equal(root.<Integer>get("cooperativeState"), 4);
                        Predicate cooperativeState2 = cb.equal(root.<Integer>get("cooperativeState"), 2);
                        predicates.add(cb.or(cooperativeState1, cooperativeState2));
                    } else {
                        Predicate cooperativeState = cb.equal(root.<Integer>get("cooperativeState"), state);
                        predicates.add(cooperativeState);
                    }
                } else if (0 == state && listType == CooTabTypeEnum.cooperativeList.getCode()) {//合作列表
                    Predicate cooperativeState1 = cb.equal(root.<Integer>get("cooperativeState"), 4);
                    Predicate cooperativeState2 = cb.equal(root.<Integer>get("cooperativeState"), 2);
                    predicates.add(cb.or(cooperativeState1, cooperativeState2));
                }
                if (!CollectionUtils.isEmpty(quantumArmyGroupIdList)) {
                    CriteriaBuilder.In<Long> in = cb.in(root.get("quantumArmyGroupId"));
                    quantumArmyGroupIdList.forEach(q -> {
                        in.value(q);
                    });
                    predicates.add(in);
                }
                if (listType == CooTabTypeEnum.applyList.getCode()) {//申请列表
                    Predicate throw_apply_delete = cb.equal(root.<Integer>get("throwApplyDelete"), 1);
                    predicates.add(throw_apply_delete);
                } else if (listType == CooTabTypeEnum.cooperativeList.getCode()) {//合作列表
                    Predicate throw_cooperative_delete = cb.equal(root.<Integer>get("throwCooperativeDelete"), 1);
                    predicates.add(throw_cooperative_delete);
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

    /*
     * @name:  findThrowCooperativeApplyList
     * @description: 查询销售合作列表
     * @param CooperativeFindReq
     * @return:CooperativeLoadRes
     * @date: 2020/12/6 下午2:15
     * @auther: zhy
     */
    public CooperativeLoadRes findSellCooperativeApplyList(Integer cooType, String authorization, CooperativeFindReq cooperativeFindReq, Integer listType) {
        StopWatch sw = new StopWatch();
        sw.start();
        Long userId = miniAdminService.getLoginUserId(authorization);
        if (userId == null) {
            throw new BusinessException("token解析失败,请稍后重试或重新登陆！");
        }
//        Long userId=2094L;
        List<Long> idList = new ArrayList<>();
        if (Objects.isNull(cooperativeFindReq.getThrowUserId())) {
//            根据用户id，查询投放负责人集合
            idList = miniAdminService.scopedAdvertisingUserIds(userId);
            if (CollectionUtils.isEmpty(idList)) {
                return null;
            }
        } else {
            idList.add(cooperativeFindReq.getThrowUserId());
        }
        log.info("查询所有投放负责人成功：{}", idList);

        Integer cooperativeType = 0;
        if (Objects.nonNull(cooperativeFindReq.getApplyUser())) {
            cooperativeType = setCooperativeType(cooType, cooperativeFindReq.getApplyUser());
        }
//        分页查询销售列表
        Specification<BusinessCooperativeBean> cooperativeList = getSellList(cooperativeFindReq, cooperativeType, idList, listType);
        log.info("sql封装成功！");
        Pageable pageable = buildPageRequest(cooperativeFindReq.getPageNumber(), cooperativeFindReq.getPageSize(), new Sort(Sort.Direction.DESC, "createTime"));
        Page<BusinessCooperativeBean> businessCooperativeBeans = cooperativeRepository.findAll(cooperativeList, pageable);
        log.info("分页查询销售列表成功：{}", businessCooperativeBeans.getContent());
//        根据字段的id，查询相关名称并赋值
        CooperativeLoadRes cooperativeLoadRes = setName(businessCooperativeBeans.getContent(), authorization, cooType, listType);
        log.info("相关名称赋值结束：{}", cooperativeLoadRes);
        cooperativeLoadRes.setTotalElements(businessCooperativeBeans.getTotalElements());
        cooperativeLoadRes.setTotalPages(businessCooperativeBeans.getTotalPages());
//        查询最新数据条数
        Integer count = findCount(cooType, idList);
        cooperativeLoadRes.setNewSize(count);
        sw.stop();
        log.info("方法耗时：{}", sw.getTotalTimeMillis());
        return cooperativeLoadRes;
    }

    /*
     * @name:
     * @description: 查询销售合作列表封装sql
     * @return: Specification<BusinessCooperativeBean>
     * @date: 2020/12/6 上午11:28
     * @auther: zhy
     */
    public Specification<BusinessCooperativeBean> getSellList(CooperativeFindReq cooperativeFindReq, Integer cooperativeType, List<Long> idList, Integer listType) {
        return new Specification<BusinessCooperativeBean>() {
            @Override
            public Predicate toPredicate(Root<BusinessCooperativeBean> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!CollectionUtils.isEmpty(idList)) {
                    CriteriaBuilder.In<Long> in = cb.in(root.get("throwUserId"));
                    idList.forEach(q -> {
                        in.value(q);
                    });
                    predicates.add(in);
                }
                if (null != cooperativeFindReq.getThrowUserId()) {
                    Predicate throwRoomId = cb.equal(root.get("throwRoomId").as(Integer.class), cooperativeFindReq.getThrowRoomId());
                    predicates.add(throwRoomId);
                }
                if (null != cooperativeFindReq.getArmyGroupId()) {
                    Predicate armyGroupId = cb.equal(root.get("armyGroupId").as(Integer.class), cooperativeFindReq.getArmyGroupId());
                    predicates.add(armyGroupId);
                }
                if (null != cooperativeFindReq.getQuantumArmyGroupId()) {
                    Predicate quantumArmyGroupId = cb.equal(root.get("quantumArmyGroupId").as(Integer.class), cooperativeFindReq.getQuantumArmyGroupId());
                    predicates.add(quantumArmyGroupId);
                }
                if (null != cooperativeFindReq.getProjectId()) {
                    Predicate projectId = cb.equal(root.get("projectId").as(Integer.class), cooperativeFindReq.getProjectId());
                    predicates.add(projectId);
                }
                if (StringUtils.isNotBlank(cooperativeFindReq.getAdChannelCode())) {
                    Predicate adChannelCode = cb.equal(root.get("adChannelCode").as(String.class), cooperativeFindReq.getAdChannelCode());
                    predicates.add(adChannelCode);
                }
                if (StringUtils.isNotBlank(cooperativeFindReq.getThrowProvinceCode())) {
                    Predicate throwProvinceCode = cb.equal(root.get("throwProvinceCode").as(String.class), cooperativeFindReq.getThrowProvinceCode());
                    predicates.add(throwProvinceCode);
                }
                Integer coo = cooperativeType;
                if (0 != cooperativeType) {
                    Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                    predicates.add(cooperativeType);
                } else if (0 == cooperativeType && null != cooperativeFindReq.getApplyState() && listType == CooTabTypeEnum.applyList.getCode()) {
                    if (cooperativeFindReq.getApplyState() == 2) {
                        coo = CooManagerTypeEnum.throwManager.getCode();
                        Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                        predicates.add(cooperativeType);
                    } else if (cooperativeFindReq.getApplyState() == 1) {
                        coo = CooManagerTypeEnum.sellManager.getCode();
                        Predicate cooperativeType = cb.equal(root.get("cooperativeType").as(Integer.class), coo);
                        predicates.add(cooperativeType);
                    }
                }
                Integer state = 0;
                if (null != cooperativeFindReq.getApplyState()) {
                    state = cooperativeFindReq.toApplyState(cooperativeFindReq.getApplyState());
                    if (null != cooperativeFindReq.getApplyUser()) {
                        if (cooperativeFindReq.getApplyUser() == CooApplyPersonEnum.myself.getCode() && cooperativeFindReq.getApplyState() == 2 || cooperativeFindReq.getApplyUser() == CooApplyPersonEnum.other.getCode() && cooperativeFindReq.getApplyState() == 1) {
                            state = -1;
                        }
                    }
                }
                if (0 != state) {
                    if (state == CooOperationEnum.confirm.getCode() && listType == CooTabTypeEnum.applyList.getCode()) {
                        Predicate cooperativeState1 = cb.equal(root.<Integer>get("cooperativeState"), 4);
                        Predicate cooperativeState2 = cb.equal(root.<Integer>get("cooperativeState"), 2);
                        predicates.add(cb.or(cooperativeState1, cooperativeState2));
                    } else {
                        Predicate cooperativeState = cb.equal(root.<Integer>get("cooperativeState"), state);
                        predicates.add(cooperativeState);
                    }
                } else if (listType == CooTabTypeEnum.cooperativeList.getCode()) {//合作列表
                    Predicate cooperativeState1 = cb.equal(root.<Integer>get("cooperativeState"), 4);
                    Predicate cooperativeState2 = cb.equal(root.<Integer>get("cooperativeState"), 2);
                    predicates.add(cb.or(cooperativeState1, cooperativeState2));
                }
                if (listType == CooTabTypeEnum.applyList.getCode()) {//申请列表
                    Predicate sell_apply_delete = cb.equal(root.<Integer>get("sellApplyDelete"), 1);
                    predicates.add(sell_apply_delete);
                } else if (listType == CooTabTypeEnum.cooperativeList.getCode()) {//合作列表
                    Predicate sell_cooperative_delete = cb.equal(root.<Integer>get("sellCooperativeDelete"), 1);
                    predicates.add(sell_cooperative_delete);
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

    //判断合作 发起方
    public Integer setCooperativeType(Integer cooType, Integer applyUser) {
        if (cooType == CooManagerTypeEnum.throwManager.getCode() && applyUser == CooApplyPersonEnum.myself.getCode() || cooType == CooManagerTypeEnum.sellManager.getCode() && applyUser == CooApplyPersonEnum.other.getCode()) {
            return 1;
        }
        if (cooType == CooManagerTypeEnum.throwManager.getCode() && applyUser == CooApplyPersonEnum.other.getCode() || cooType == CooManagerTypeEnum.sellManager.getCode() && applyUser == CooApplyPersonEnum.myself.getCode()) {
            return 2;
        }
        return 0;
    }

    /*
     * @name:
     * @description: 根据id查询名称 赋值
     * @return: CooperativeLoadRes
     * @date: 2020/12/8 下午1:58
     * @auther: zhy
     */
    public CooperativeLoadRes setName(List<BusinessCooperativeBean> businessCooperativeBean, String authorization, Integer cooType, Integer listType) {
        CooperativeLoadRes cooperativeLoadVO = new CooperativeLoadRes();
        List<CooperativeShowRes> cooperativeShowRess = new ArrayList<>();
//      获取项目省份渠道名称列表
        Map<Integer, String> projectMap = getProjectMap(authorization);
        Map<String, String> channelMap = getChannelMap(authorization);
        Map<String, String> provinceMap = getProvinceMap(authorization);

//        根据合作列表中的各个字段id，查询对应的名称
        for (BusinessCooperativeBean c : businessCooperativeBean) {
            CooperativeShowRes cooperativeShowRes = new CooperativeShowRes();
            cooperativeShowRes.setId(c.getId());
            cooperativeShowRes.setCooperativeType(c.getCooperativeType());
            cooperativeShowRes.setCreateTime(c.getCreateTime());

            UserVO userSimpleInfo = miniAdminService.getUserSimpleInfo(c.getCreateUserId());
            cooperativeShowRes.setCreateUser(userSimpleInfo.getNickname());
            cooperativeShowRes.setCreateUserEmail(userSimpleInfo.getEmail());

            UserVO userSimple = miniAdminService.getUserSimpleInfo(c.getThrowUserId());
            cooperativeShowRes.setThrowUser(userSimple.getNickname());
            cooperativeShowRes.setThrowUserEmail(userSimple.getEmail());

            cooperativeShowRes.setThrowRoom(miniAdminService.getDeptName(c.getThrowRoomId()));
            cooperativeShowRes.setArmyGroup(miniAdminService.getDeptName(c.getArmyGroupId()));
            cooperativeShowRes.setQuantumArmyGroup(miniAdminService.getDeptName(c.getQuantumArmyGroupId()));

            cooperativeShowRes.setProject(projectMap.get(c.getProjectId()));
            cooperativeShowRes.setAdChannel(channelMap.get(c.getAdChannelCode()));
            cooperativeShowRes.setThrowProvince(provinceMap.get(c.getThrowProvinceCode()));
            cooperativeShowRes.toCooperativeState(c.getCooperativeState(), c.getCooperativeType(), cooType, listType);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-DD");
            String create = simpleDateFormat.format(c.getCreateTime());
            String now = simpleDateFormat.format(new Date());
            if (create.equals(now)) {
                cooperativeShowRes.toNewOne(c.getCooperativeType(), cooType);
            }

            cooperativeShowRess.add(cooperativeShowRes);
        }
        cooperativeLoadVO.setCooperativeShowVOS(cooperativeShowRess);
        return cooperativeLoadVO;
    }

    /*
     * @name:
     * @description: 查询最新数据条数
     * @param cooType
     * @return:
     * @date: 2020/12/10 下午5:04
     * @auther: zhy
     *
     */
    public Integer findCount(Integer cooType, List<Long> idList) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String now = dateFormat.format(new Date());
        Integer count = 0;
        if (cooType == 1) {
            count = cooperativeRepository.findThrowCount(cooType, now, idList);
        }
        if (cooType == 2) {
            count = cooperativeRepository.findSellCount(cooType, now, idList);
        }
        return count;
    }

    //        获取项目列表
    public Map<Integer, String> getProjectMap(String token) {
        List<BusinessItemInfoVO> projectList = dictionariesBaseService.getItemInfo(token);
        Map<Integer, String> projectMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(projectList)) {
            projectMap = projectList.stream().collect(Collectors.toMap(BusinessItemInfoVO::getId, BusinessItemInfoVO::getItemName));
        }
        return projectMap;
    }

    //        获取渠道列表
    public Map<String, String> getChannelMap(String token) {
        List<BusinessChannelInfoVO> channelList = dictionariesBaseService.getChannelInfoList(token);
        Map<String, String> channelMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(channelList)) {
            channelMap = channelList.stream().collect(Collectors.toMap(BusinessChannelInfoVO::getCode, BusinessChannelInfoVO::getName));
        }
        return channelMap;
    }

    //        获取省份列表
    public Map<String, String> getProvinceMap(String token) {
        List<BusinessCity> provinceList = dictionariesBaseService.getProvinceList();
        Map<String, String> provinceMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(provinceList)) {
            provinceMap = provinceList.stream().collect(Collectors.toMap(BusinessCity::getCode, BusinessCity::getName));
        }
        return provinceMap;
    }

}
